<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 确保引入ECharts库 -->
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.0/dist/echarts.min.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <title>宿舍评分管理系统</title>
    <style>
        :root {
            --primary-color: #1890ff;
            --border-color: #d9d9d9;
        }

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 12px;
            margin-top: 20px;
        }

        .btn-prev,
        .btn-next {
            padding: 8px 16px;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            background: #fff;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .btn-prev:hover,
        .btn-next:hover {
            color: var(--primary-color);
            border-color: var(--primary-color);
            background-color: rgba(24, 144, 255, 0.05);
        }

        .btn-prev:disabled,
        .btn-next:disabled {
            color: var(--border-color);
            border-color: var(--border-color);
            cursor: not-allowed;
            background-color: #f5f5f5;
        }

        #pageInfo {
            min-width: 70px;
            text-align: center;
            font-size: 14px;
        }

        .table-striped tbody tr:nth-of-type(odd) {
            background-color: #f5f5f5;
        }

        .table-striped tbody tr.highlight {
            background-color: #eaeaea;
        }

        .table td.text-center {
            text-align: center;
        }

        /* 新增模态框样式 */
        .modal-content {
            padding: 24px;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
    </style>
</head>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!-- 在<head>中添加ECharts引用 -->
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.0/dist/echarts.min.js"></script>

<body>
<div class="container">
    <!-- 搜索和操作栏 -->
    <div class="bg-light p-3 mb-3">
        <div class="d-flex justify-content-between align-items-center">
            <div class="me-3">宿舍评分管理</div>
            <div class="d-flex align-items-center">
                <input type="text" placeholder="评分ID" class="form-control me-2" id="roomIdSearch" style="width: 200px;">
                <button class="btn btn-secondary me-2" onclick="show()" style="background-color: #2d9249">查询</button>
                <!-- 排行榜筛选栏 -->
                <div class="me-3">
                    <label class="me-2">选择月份：</label>
                    <input type="month" class="form-control me-2" id="rankMonth" value="${currentMonth}">
                    <select class="form-control me-2" id="sortType">
                        <option value="avgDesc">平均分从高到低</option>
                        <option value="avgAsc">平均分从低到高</option>
                        <option value="totalDesc">总分从高到低</option>
                        <option value="totalAsc">总分从低到高</option>
                    </select>
                </div>
                <!-- 生成排行榜按钮（绑定新函数） -->
                <button class="btn btn-success me-2" onclick="generateRanking()" style="background-color: #6a6b6c">生成排行榜</button>
                <button class="btn btn-primary me-2" id="addScoreBtn" data-bs-toggle="modal" data-bs-target="#addScoreModal">新增</button>

            </div>
        </div>
    </div>

    <!-- 新增评分模态框 -->
    <div class="modal fade" id="addScoreModal" tabindex="-1" aria-labelledby="addScoreModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addScoreModalLabel">新增宿舍评分</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form>
                        <div class="mb-3">
                            <label class="form-label">房间号</label>
                            <input type="number" class="form-control" id="addRoomId" name="roomId" required>
                        </div>
                        <div class="mb-3">
                            <label for="addCheckDate" class="form-label">检查日期</label>
                            <input type="date" class="form-control" id="addCheckDate" name="checkDate" required>
                        </div>
                        <div class="mb-3">
                            <label for="addHygieneScore" class="form-label">卫生评分</label>
                            <input type="number" class="form-control" id="addHygieneScore" name="hygieneScore" min="0"
                                   max="100">
                        </div>
                        <div class="mb-3">
                            <label for="addDisciplineScore" class="form-label">纪律评分</label>
                            <input type="number" class="form-control" id="addDisciplineScore" name="disciplineScore"
                                   min="0" max="100">
                        </div>
                        <div class="mb-3">
                            <label for="addInspector" class="form-label">检查人员</label>
                            <input type="text" class="form-control" id="addInspector" name="inspector" maxlength="100">
                        </div>

                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                            <button type="button" class="btn btn-primary" id="confirmAddScore">确认添加</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- 修改评分模态框 -->
    <div class="modal fade" id="editScoreModal" tabindex="-1" aria-labelledby="editScoreModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editScoreModalLabel">修改宿舍评分信息</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form>
                        <input type="hidden" id="editScoreId" name="scoreId">
                        <div class="mb-3">
                            <label class="form-label">关联房间ID</label>
                            <input type="number" class="form-control" id="editRoomId" name="roomId" required>
                        </div>
                        <div class="mb-3">
                            <label for="editCheckDate" class="form-label">检查日期</label>
                            <input type="date" class="form-control" id="editCheckDate" name="checkDate" required>
                        </div>
                        <div class="mb-3">
                            <label for="editHygieneScore" class="form-label">卫生评分</label>
                            <input type="number" class="form-control" id="editHygieneScore" name="hygieneScore" min="0"
                                   max="100">
                        </div>
                        <div class="mb-3">
                            <label for="editDisciplineScore" class="form-label">纪律评分</label>
                            <input type="number" class="form-control" id="editDisciplineScore" name="disciplineScore"
                                   min="0" max="100">
                        </div>
                        <div class="mb-3">
                            <label for="editInspector" class="form-label">检查人员</label>
                            <input type="text" class="form-control" id="editInspector" name="inspector" maxlength="100">
                        </div>

                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                            <button type="button" class="btn btn-primary" id="confirmEditScore">确认修改</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- 评分信息表格 -->
    <table class="table table-striped table-bordered" id="scoresTable">
        <thead>
        <tr>
            <th>评分ID</th>
            <th>房间ID</th>
            <th>检查日期</th>
            <th>卫生评分</th>
            <th>纪律评分</th>
            <th>检查人员</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>

        </tbody>
        <tfoot>
        <tr>
            <td colspan="7">
                <div class="pagination">
                    <button class="btn-prev" onclick="page(1)">上一页</button>
                    <span id="pageInfo">第 1 页</span>
                    <button class="btn-next" onclick="page(2)">下一页</button>
                </div>
            </td>
        </tr>
        </tfoot>
    </table>
</div>

<input type="hidden" id="currentPage" value="0">
<input type="hidden" id="totalPages" value="1">
<input type="hidden" id="pages" value="0">
<!-- 引入必要的JS库（与原页面一致） -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<!--分页-->
<script>
    let currentPage = 0;
    let totalPages = 1;

    // 页面加载时初始化
    $(document).ready(function () {
        show();
    });

    // 加载楼栋下拉框选项
    function loadBuildings() {
        $.ajax({
            url: '<%=request.getContextPath()%>/dormscoresController?op=cxj',
            type: 'GET',
            success: function (response) {
                debugger
                const buildings = JSON.parse(response);
                let options = "";
                buildings.list.forEach(building => {
                    options += '<tr>' +
                        '<th>' + building.score_id + '</th>' +
                        '<th>' + building.room_number + '</th>' +
                        '<th>' + building.check_date + '</th>' +
                        '<th>' + building.hygiene_score + '</th>' +
                        '<th>' + building.discipline_score + '</th>' +
                        '<th>' + building.inspector + '</th>' +
                        '<th>' +
                        '<button id="btn-warning" class="btn btn-warning me-1 edit-btn" ' +
                        'data-id="' + building.score_id + '" ' +
                        'data-room-id="'+building.room_number +'" ' +
                        'data-check-date="'+building.check_date+'" '+
                        'data-hygiene-score="'+building.hygiene_score+'" ' +
                        'data-discipline-score="'+building.discipline_score+'" ' +
                        'data-inspector="'+building.inspector+'"  onclick="updateData(this)">修改</button>' +
                        '<button class="btn btn-danger" ' +
                        'onclick="scj('+building.score_id+',this)">删除</button>' +
                        '</th>' +
                        '</tr>';
                });
                $("table tbody").html(options);
            },
            error: function () {
                alert('请求失败，请检查网络连接');
            }
        });
    }
    let allScoresData = [];
    // 统一查询和分页功能
    function show(pageNum) {
        const roomIdSearch = $('#roomIdSearch').val();

        $.ajax({
            url: '<%=request.getContextPath()%>/dormscoresController',
            type: 'GET',
            data: {
                op: 'cxj',
                page: pageNum || currentPage,
                lid: roomIdSearch
            },
            success: function (response) {
                try {
                    const data = JSON.parse(response);
                    renderTable(data.list);

                    // 合并数据到全局缓存
                    allScoresData = [...allScoresData, ...data.list];

                    $("#pages").val(data.page);
                    updatePagination(data.page, data.totalPages);
                } catch (e) {
                    console.error('数据解析错误:', e);
                    alert('数据加载失败，请稍后重试');
                }
            },
            error: function () {
                alert('请求失败，请检查网络连接');
            }
        });
    }

    // 渲染表格数据
    function renderTable(data) {
        const tbody = $('#scoresTable tbody');
        let row = "";
        tbody.empty();

        $.each(data, function (index, room2) {
            row += '<tr>' +
                '<td>' + room2.score_id + '</td>' +
                '<td>' + room2.room_number + '</td>' +
                '<td>' + room2.check_date + '</td>' +
                '<td>' + room2.hygiene_score + '</td>' +
                '<td>' + room2.discipline_score + '</td>' +
                '<td>' + room2.inspector + '</td>' +
                '<td>' +
                '<button id="btn-warning" class="btn btn-warning me-1 edit-btn" ' +
                'data-id="' + room2.score_id + '" ' +
                'data-room-id="'+room2.room_number +'" ' +
                'data-check-date="'+room2.check_date+'" '+
                'data-hygiene-score="'+room2.hygiene_score+'" ' +
                'data-discipline-score="'+room2.discipline_score+'" ' +
                'data-inspector="'+room2.inspector+'"  onclick="updateData(this)">修改</button>' +
                '<button class="btn btn-danger" ' +
                'onclick="scj('+room2.score_id+',this)">删除</button>' +
                '</td>' +
                '</tr>';
        });

        tbody.append(row);
    }

    // 更新分页状态
    function updatePagination(currentPage, totalPages) {
        $('#pageInfo').text("第" + (currentPage + 1) + "页");
        $('.btn-prev').prop('disabled', currentPage === 0);
        $('.btn-next').prop('disabled', currentPage >= totalPages - 1);

        // // 保存当前页和总页数
        // currentPage = currentPage;
        // totalPages = totalPages;
    }

    // 分页按钮点击事件
    function page(newPage) {
        let page = parseInt($("#pages").val());
        if (newPage === 1) {
            page--;
        } else {
            page++;
        }
        currentPage = page;
        show(currentPage);
    }



    // 删除宿舍房间函数
    function scj(id, that) {
        if (confirm("确定要删除房间ID为 " + id + " 的宿舍房间吗？")) {
            $.post("<%=request.getContextPath()%>/dormscoresController", {
                op: "scj",
                id: id
            }, function () {
                alert("删除成功");
                that.parentNode.parentNode.remove();
            }).fail(function () {
                alert("删除失败");
            });
        }
    }

    // 新增评分功能
    $(document).ready(function () {
        // 确认添加评分
        $("#confirmAddScore").click(function () {
            const formData = {
                roomId: $("#addRoomId").val(),
                checkDate: $("#addCheckDate").val(),
                hygieneScore: $("#addHygieneScore").val(),
                disciplineScore: $("#addDisciplineScore").val(),
                inspector: $("#addInspector").val()
            };

            if (!formData.roomId || !formData.checkDate ||!formData.hygieneScore ||!formData.disciplineScore  ||!formData.inspector) {
                alert("请填写完整");
                return;
            }
            $.ajax({
                url: "<%=request.getContextPath()%>/dormscoresController",
                type: "POST",
                data: {
                    op: 'add3',
                    roomId: formData.roomId,
                    checkDate: formData.checkDate,
                    hygieneScore: formData.hygieneScore,
                    disciplineScore: formData.disciplineScore,
                    inspector: formData.inspector
                },
                success: function (response) {
                    alert(response);
                    $('#addScoreModal').modal('hide');
                    show();
                },
                error: function () {
                    alert("添加失败，请稍后再试");
                    loadBuildings();
                }
            });
        });
       console.log("1")
        // 关闭模态框时清空表单
        $('#addScoreModal').on('hidden.bs.modal', function () {
            $(this).find('form')[0].reset();
        });
    });

    // 绑定修改按钮点击事件（事件委托）
    function updateData(that){
        debugger
        const scoreId = $(that).data('id');
        const roomId = $(that).data('room-id');
        const checkDate = $(that).data('check-date');
        const hygiene = $(that).data('hygiene-score');
        const discipline = $(that).data('discipline-score');
        const inspector = $(that).data('inspector');

        $("#editScoreId").val(scoreId);
        $("#editRoomId").val(roomId);
        $("#editCheckDate").val(checkDate);
        $("#editHygieneScore").val(hygiene);
        $("#editDisciplineScore").val(discipline);
        $("#editInspector").val(inspector);

        $('#editScoreModal').modal('show');
    }

    // 修改评分功能
    $(document).ready(function () {
        // 确认修改评分
        $("#confirmEditScore").click(function () {
            const formData = {
                scoreId: $("#editScoreId").val(),
                roomId: $("#editRoomId").val(),
                checkDate: $("#editCheckDate").val(),
                hygieneScore: $("#editHygieneScore").val(),
                disciplineScore: $("#editDisciplineScore").val(),
                inspector: $("#editInspector").val()
            };
            if (!formData.roomId || !formData.checkDate || !formData.hygieneScore || !formData.disciplineScore|| !formData.inspector) {
                alert("房间ID和检查日期为必填项");
                return;
            }
            $.ajax({
                url: "<%=request.getContextPath()%>/dormscoresController",
                type: "POST",
                data: {
                    op: 'update3',
                    scoreId: formData.scoreId,
                    roomId: formData.roomId,
                    checkDate: formData.checkDate,
                    hygieneScore: formData.hygieneScore,
                    disciplineScore: formData.disciplineScore,
                    inspector: formData.inspector
                },
                success: function (response) {
                    alert(response);
                    $('#editScoreModal').modal('hide');
                    backdrop:false;
                     show();
                    loadBuildings();
                },

            });
        });

        // 关闭模态框时清空表单
        $('#editScoreModal').on('hidden.bs.modal', function () {
            $(this).find('form')[0].reset();
        });
    });

    // 导出Excel功能
    function exportToExcel() {
        try {
            // 获取表格
            var table = document.getElementById("tableId");
            if (!table) {
                throw new Error("未找到表格元素");
            }
            // 检查是否有数据
            var rows = table.querySelectorAll("tbody tr");
            if (rows.length === 0) {
                alert("没有数据可导出");
                return;
            }
            // 创建工作簿和工作表
            var wb = XLSX.utils.book_new();
            var ws = XLSX.utils.table_to_sheet(table);

            // 设置列宽
            var cols = [];
            var headerCells = table.querySelectorAll("thead th");
            headerCells.forEach(function (header) {
                var maxLength = header.innerText.length;
                rows.forEach(function (row) {
                    var cell = row.querySelector("td:nth-child(" + (cols.length + 1) + ")");
                    if (cell) {
                        maxLength = Math.max(maxLength, cell.innerText.length);
                    }
                });
                cols.push({wch: Math.min(maxLength + 2, 50)}); // 限制最大宽度
            });
            ws['!cols'] = cols;

            // 添加工作表到工作簿
            XLSX.utils.book_append_sheet(wb, ws, "宿舍房间信息");

            // 生成文件名
            var date = new Date();
            var fileName = "宿舍房间信息_" +
                date.getFullYear() +
                (date.getMonth() + 1).toString().padStart(2, '0') +
                date.getDate().toString().padStart(2, '0') +
                ".xlsx";

            // 导出文件
            XLSX.writeFile(wb, fileName);
        } catch (error) {
            console.error("导出Excel时发生错误:", error);
            alert("导出失败：" + error.message);
        }
    }

    // 生成排行榜
    function generateRanking() {
        console.log("生成排行榜触发");
        const selectedMonth = $('#rankMonth').val();
        const sortType = $('#sortType').val();
        const table = document.getElementById("scoresTable");
        const rows = Array.from(table.querySelectorAll("tbody tr"));


        // 直接使用缓存的所有数据
        const filteredData = allScoresData.filter(item => {
            const checkDate = new Date(item.check_date);
            const yearMonth = checkDate.toISOString().split('T')[0].split('-').slice(0, 2).join('-');
            return yearMonth === selectedMonth;
        });


        if (rows.length === 0) {
            alert("表格中没有数据");
            return;
        }

        // 过滤并计算指定月份数据
        const monthlyScores = {};
        rows.forEach(row => {
            const cells = row.cells;
            const checkDate = new Date(cells[2].textContent);
            const yearMonth = checkDate.toISOString().split('T')[0].split('-').slice(0, 2).join('-');

            if (yearMonth === selectedMonth) {
                const roomId = cells[1].textContent;
                const hygiene = parseInt(cells[3].textContent) || 0;
                const discipline = parseInt(cells[4].textContent) || 0;
                const total = hygiene + discipline;

                if (!monthlyScores[roomId]) {
                    monthlyScores[roomId] = { roomId, totalScore: 0, count: 0, avgScore: 0 };
                }

                monthlyScores[roomId].totalScore += total;
                monthlyScores[roomId].count++;
                monthlyScores[roomId].avgScore = (monthlyScores[roomId].totalScore / monthlyScores[roomId].count).toFixed(2);
            }
        });

        const sortedScores = Object.values(monthlyScores);

        if (sortedScores.length === 0) {
            alert(`该月份（${selectedMonth}）没有评分数据`);
            return;
        }

        // 排序
        sortedScores.sort((a, b) => {
            switch (sortType) {
                case 'avgDesc': return b.avgScore - a.avgScore;
                case 'avgAsc': return a.avgScore - b.avgScore;
                case 'totalDesc': return b.totalScore - a.totalScore;
                case 'totalAsc': return a.totalScore - b.totalScore;
                default: return b.avgScore - a.avgScore;
            }
        });

        // 导出Excel
        exportRankingToExcel(sortedScores, selectedMonth);

        // 尝试渲染图表（添加错误处理）
        try {
            renderRankingChart(sortedScores, selectedMonth);
        } catch (e) {
            console.error("图表渲染失败:", e);
            alert("图表生成失败，但Excel已导出");
        }
    }

    // 导出排行榜数据到Excel
    function exportRankingToExcel(data, month) {
        const wsData = [
            ["排名", "房间ID", "检查次数", "总分", "平均分"],
            ...data.map((item, index) => [
                index + 1,
                item.roomId,
                item.count,
                item.totalScore,
                item.avgScore
            ])
        ];

        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.aoa_to_sheet(wsData);
        ws['!cols'] = [{wch: 6}, {wch: 12}, {wch: 10}, {wch: 10}, {wch: 12}];
        XLSX.utils.book_append_sheet(wb, ws, `排行_${month}`);

        const fileName = `宿舍评分排行_${month}.xlsx`;
        XLSX.writeFile(wb, fileName);
    }

    // 渲染排行榜图表（添加错误处理）
    function renderRankingChart(data, month) {
        const chartDom = document.createElement('div');
        chartDom.style.width = '600px';
        chartDom.style.height = '400px';

        const myChart = echarts.init(chartDom);
        const option = {
            title: { text: `[${month}] 宿舍评分排行榜` },
            xAxis: { data: data.map(item => item.roomId) },
            yAxis: { name: '分数' },
            series: [
                { type: 'bar', name: '平均分', data: data.map(item => parseFloat(item.avgScore)) }
            ]
        };

        myChart.setOption(option);

        // 渲染排行榜图表（修复版）
        function renderRankingChart(data, month) {
            const chartDom = document.createElement('div');
            chartDom.style.width = '600px';
            chartDom.style.height = '400px';

            const myChart = echarts.init(chartDom);
            const option = {
                title: { text: `[${month}] 宿舍评分排行榜` },
                xAxis: { data: data.map(item => item.roomId) },
                yAxis: { name: '分数' },
                series: [
                    { type: 'bar', name: '平均分', data: data.map(item => parseFloat(item.avgScore)) }
                ]
            };

            myChart.setOption(option);

            // 创建模态框
            const modalDiv = document.createElement('div');
            modalDiv.className = 'modal fade';
            modalDiv.innerHTML = `
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">${month} 评分排行</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body d-flex justify-content-center">
                    ${chartDom.outerHTML}
                </div>
            </div>
        </div>
    `;

            // 将模态框添加到文档中
            document.body.appendChild(modalDiv);

            // 手动初始化模态框
            const modal = new bootstrap.Modal(modalDiv);
            modal.show();

            // 模态框关闭后移除DOM元素
            modalDiv.addEventListener('hidden.bs.modal', () => {
                document.body.removeChild(modalDiv);
            });
        }
    }
</script>
</body>
</html>
